public class test1 {
    //力扣   38. 外观数列

    public static void main(String[] args) {
        System.out.println(countAndSay2(4));
    }
    public static String countAndSay(int n) {
        if(n==1){
            return "1";
        }
        String ret = "1";
        while(n!=1){
            StringBuilder newstr = new StringBuilder();
            int left = 0,right = 1;
            char[] arr = ret.toCharArray();
            while(right<arr.length){

                while(right<arr.length && arr[left]==arr[right]){
                    right++;
                }
                int count = right-left;
                char temp = arr[left];
                newstr.append(count+"");
                newstr.append(temp);
            }
            int count = right-left;
            char temp = arr[left];
            newstr.append(count+"");
            newstr.append(temp);
            ret = newstr.toString();
            n--;
        }
        return ret;
    }

    public static String countAndSay2(int n) {
        // if(n==1){
        //     return "1";
        // }
        String ret = "1";
        for(int i = 1;i<n;i++){
            StringBuilder newstr = new StringBuilder();
            int len = ret.length();

            // char[] arr = ret.toCharArray();
            for(int left = 0,right = 0;right<len;){

                while(right<len && ret.charAt(left)==ret.charAt(right)){
                    right++;
                }

                newstr.append(Integer.toString(right-left));
                newstr.append(ret.charAt(left));
                left = right;
            }
            // int count = right-left;
            // char temp = ret.charAt(left);
            // newstr.append(count+"");
            // newstr.append(temp);
            ret = newstr.toString();
            // n--;
        }
        return ret;
    }
}
